import service from "@/utils/request.ts";
import service_file from "@/utils/request-file.ts";
import {COMPLETE_PRE} from '@/api/port-info.ts'
import axios from "axios";
import {REQUEST_AUTH_IDENT, RESPONSE_CODE_SUCCESS} from "@/config/common-config.ts";
import {errorMessageTip, successMessageTip} from "@/utils/tip-utils.ts";

/**
 * 获取省市区下拉框
 * @param params
 */
export async function getAreaListDropBoxReq(params: any) {
    return service({
        baseURL: COMPLETE_PRE,
        url: 'admin/common/getAreaListDropBox',
        method: 'POST',
        data: params
    });
}

/**
 * 获取参数配置信息
 * @param params 参数
 */
export async function getValueByKeyReq(params: any) {
    return service({
        baseURL: COMPLETE_PRE,
        url: 'login/userOperate/login',
        method: 'POST',
        data: params
    });
}

/**
 * 上传文件
 * @param params 参数
 */
export async function uploadFileReq(params: any) {
    return service_file({
        baseURL: COMPLETE_PRE,
        url: 'admin/common/uploadFile',
        method: 'POST',
        data: params
    });
}

/**
 * 下载日志文件
 * @param params 参数
 */
export async function downloadLogFileReq(params: any) {
    const fileName = params.fileName;

    const response: any = await axios.get(COMPLETE_PRE + 'admin/common/downloadLogFile/' + fileName, {
        responseType: 'blob',
        headers: {
            "token": localStorage.getItem(REQUEST_AUTH_IDENT)
        },
    });

    if (response.status === RESPONSE_CODE_SUCCESS){
        successMessageTip("下载成功")
    } else {
        errorMessageTip("下载失败")
    }

    const url = window.URL.createObjectURL(new Blob([response.data], { type: response.headers['content-type'] }));
    handleFileRespFun(url, fileName);
}

/**
 * 下载文件
 * @param params 参数
 */
export async function downloadFileReq(params: any) {
    const fileId = params.fileId

    const response: any = await axios.get(COMPLETE_PRE + 'admin/common/downloadFile/' + fileId, {
        responseType: 'blob',
        headers: {
            "token": localStorage.getItem(REQUEST_AUTH_IDENT)
        }
    });

    if (response.status === RESPONSE_CODE_SUCCESS){
        successMessageTip("下载成功")
    } else {
        errorMessageTip("下载失败")
    }

    const contentDisposition = response.headers['content-disposition'];
    const fileNameEncoded = contentDisposition.split('filename*=UTF-8\'\'')[1];
    const fileName = decodeURIComponent(fileNameEncoded); // 解码中文文件名

    const blob = new Blob([response.data], { type: response.headers['content-type'] });
    const url = window.URL.createObjectURL(blob);

    handleFileRespFun(url, fileName);
}

/**
 * 统一处理文件下载操作
 * @param url 路径
 * @param fileName 文件名
 */
const handleFileRespFun = (url:string, fileName: string) => {
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', fileName);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
}

